using System;
using System.IO;
using System.Runtime.Serialization;

namespace ShuttleBus.Serialization
{
    [Obsolete("Deprecating in favor of Json Serialization")]
    public class XmlSerializer : ISerializer
    {
        public void Serialize(IStream stream, TransportMessage objectToSerialize)
        {
            var serializer = new DataContractSerializer(typeof(TransportMessage), new[]{Type.GetType(objectToSerialize.Type)});
            serializer.WriteObject(stream.BaseStream, objectToSerialize);
            stream.BaseStream.Position = 0;
        }

        public object Deserialize(IStream stream)
        {
            var reader = new StreamReader(stream.BaseStream);
            var foo = reader.ReadToEnd();
            var startIndex = foo.IndexOf("<Type>") + 6;
            var type = foo.Substring(startIndex);
            type = type.Substring(0, type.IndexOf("</Type>"));
            stream.BaseStream.Position = 0;

            var serializer = new DataContractSerializer(typeof(TransportMessage), new[] { Type.GetType(type) });

            var readObject = serializer.ReadObject(stream.BaseStream);
            return ((TransportMessage)readObject).Payload;
        }
    }
}